package com.mediacloud.app.newsmodule.fragment.video.vod

import android.annotation.SuppressLint
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.*
import androidx.recyclerview.widget.SimpleItemAnimator
import com.blankj.utilcode.util.NetworkUtils
import com.eventTrack.TXReportManager
import com.mediacloud.app.fbnavsk.SecondNav
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.ListPreLoadKit
import com.mediacloud.app.newsmodule.fragment.ListPreLoadTool.preLoad2
import com.mediacloud.app.newsmodule.fragment.NotIntrestEvent
import com.mediacloud.app.newsmodule.fragment.video.x.RVListVideoKit
import com.mediacloud.app.newsmodule.utils.BindEventBus
import com.mediacloud.app.newsmodule.utils.readData
import com.mediacloud.app.newsmodule.utils.saveData
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.utils.ExposurePoolService
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_info_flow.*
import kotlinx.android.synthetic.main.fragment_tab_news_list.listView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONException
import kotlin.math.abs

class VideoNewsListFragmentX : HqyNavFragment(), OnRefreshLoadMoreListener, ToolBarActionF5OrTop {


    var catalogID: String? = null
    private var catalogItem: CatalogItem? = null
    private var pageSize = 20
    private var adapter: VideoNewListAdapterX? = null
    private var mRVListVideoKit: RVListVideoKit? = null
    private var preLoadKit: ListPreLoadKit<ArticleListData>? = null

    override fun getLayoutResID(): Int {
        return R.layout.fragment_info_flow
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        navPaddingTopMatch()
    }

    override fun initArgs() {
        super.initArgs()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments!!.getString("id")
            catalogItem = saveInstanceArguments!!.getParcelable("catalog")
        }
    }

    override fun initView() {

        loadingView = findViewById(R.id.mLoadingView);
        initStateView();
        retryTips?.setOnClickListener {
            if (currentState != TYPE_LOADING) {
                if (NetworkUtils.isConnected()) {
                    showStateView(TYPE_LOADING, false)
                    onRefresh(refreshLayout)
                }
            }
        }
        showStateView(TYPE_LOADING, false)
        refreshLayout.setOnRefreshLoadMoreListener(this)


        preLoadKit = object : ListPreLoadKit<ArticleListData>(requireContext(), refreshLayout) {
            override fun onSetData(data: ArticleListData) {
                setData(data)
            }

            override fun onPreload(preNum: Int) {
                preload(preNum)
            }

        }
        adapter = VideoNewListAdapterX(requireContext())
        adapter?.catalogItem = catalogItem
        refreshLayout.setOnRefreshLoadMoreListener(this)
        refreshLayout.setEnableLoadMore(false)
        val manager = LinearLayoutManager(requireContext())
        recyclerView.layoutManager = manager
        recyclerView.adapter = adapter
        val itemAnimator = recyclerView.itemAnimator
        if (itemAnimator is SimpleItemAnimator) {
            itemAnimator.supportsChangeAnimations = false
        }
        mRVListVideoKit = RVListVideoKit(requireContext(), recyclerView, this)
        parentFragment?.let {
            if (it is SecondNav) {
                mRVListVideoKit?.playerView?.viewPlayer = it.viewPager
            }
        }

        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var state = SCROLL_STATE_IDLE
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                    //性滑动的速度小于20我们就去区屏幕中可见的视频进行缓存
                    if(state == SCROLL_STATE_SETTLING && abs(dy) < 20){
                        checkPreLoad()
                    }
                val lastVisibleItem = manager.findLastVisibleItemPosition()
                if (lastVisibleItem == manager.itemCount - 1) {
                    preLoadKit?.onLoadMore()
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    SCROLL_STATE_DRAGGING->{
                        state = SCROLL_STATE_DRAGGING
                        checkPreLoad()
                    }
                    SCROLL_STATE_SETTLING ->{
                        state = SCROLL_STATE_SETTLING;
                    }
                    SCROLL_STATE_IDLE ->{
                        state = SCROLL_STATE_IDLE
                        app_jhapp_video_imp()
                    }
                    else ->{
                        state = SCROLL_STATE_IDLE
                    }
                }
            }
            private fun checkPreLoad(){
                val firstVisibleItem = manager.findFirstVisibleItemPosition()
                val lastVisibleItem = manager.findLastVisibleItemPosition()
                try {
                    val articleList: MutableList<ArticleItem> = ArrayList()
                    for (i in firstVisibleItem..lastVisibleItem){
                        articleList.add(adapter!!.data[i])
                    }
                    preLoad2(requireContext(), articleList)
                }catch (e:Exception){
                    e.printStackTrace()
                }
            }
        })

        val dataResult = this.readData("$catalogID", ArticleListData::class.java)
        if (dataResult != null && dataResult.articleList.size > 0) {
            showStateView(TYPE_LOADING, false)
            setData(dataResult)
        } else {
            showStateView(TYPE_LOADING, false)
            getDate()
        }
        BindEventBus(this, adapter)
    }

    //private var pendingIndex = -1;
    override fun onLoadMore(refreshLayout: RefreshLayout) {
        Log.w(ListPreLoadKit.LTAG, "触发了 RefreshLayout onLoadMore")
        preLoadKit?.getMoreDate()
    }

    override fun unChosoed() {
        super.unChosoed()
        mRVListVideoKit?.stopPlay()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        preLoadKit?.onRefresh()
        mRVListVideoKit?.reset()
        getDate()
    }


    // var nextInfoFlowSmallAtLeft = true
    private fun getDate() {
        DataInvokeUtil.getContentList(catalogID, preLoadKit!!.pageNum, pageSize, null).map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            preLoadKit?.hasMore = temp.more
            temp
        }.onErrorReturn { null }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<ArticleListData> {
                override fun onSubscribe(d: Disposable) {}

                @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
                override fun onNext(t: ArticleListData) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                    preLoadKit?.preLoadData?.add(t)
                    setData(t)
                    dataReady = true
                    if(hadChoosed){
                        app_jhapp_video_imp()
                    }
                    preLoadKit?.preload()
                    try {
                        recyclerView.postDelayed({
                            if (userVisibleHint || !hidden) {
                                mRVListVideoKit?.let {
//                                    if (it.pendingStopTimeStamp == 0L) {//说明还没有切走
//
//
//                                    }
                                    try {
                                        mRVListVideoKit?.mDy = 1
                                        mRVListVideoKit?.initPendingPlay()
                                    } catch (e: Exception) {
                                        e.printStackTrace()
                                    }
                                }

                            }

                        }, 1000)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                }

                override fun onError(e: Throwable) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh(false)
                    refreshLayout.finishLoadMore()
                    if (adapter?.data?.size == 0) {
                        showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                    } else {
                        closeStateView()
                    }
                }

                override fun onComplete() {

                }
            })

    }


    private fun setData(t: ArticleListData) {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed)
            return

        if (preLoadKit!!.pageNum == 1) {
            adapter?.setItems(t.articleList)

            var isCacheData = t.orginData.optInt("is_cache", 0) == 1
            if (!isCacheData) {
                try {
                    t.orginData.put("is_cache", 1)
                    saveData("$catalogID", t.orginData.toString() + "")
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
            if (isCacheData) {
                onRefresh(refreshLayout)
            }

        } else {
            adapter?.addItems(t.articleList)
        }
        if (adapter?.data?.size == 0) {
            showStateView(TYPE_NO_CONTENT, false)
        } else {
            closeStateView()
        }
    }

    @SuppressLint("CheckResult")
    private fun preload(preNum: Int) {
        DataInvokeUtil.getContentList(catalogID, preNum, pageSize, null).map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            temp
        }.subscribeOn(Schedulers.io()).onErrorReturn { null }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<ArticleListData> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: ArticleListData) {
                    preLoadKit?.hasMore = t.more
                    preLoadKit?.onPreloadSuccess(t, preNum)
                }

                override fun onError(e: Throwable) {
                    preLoadKit?.onPreloadFail(preNum)
                }

                override fun onComplete() {

                }
            })
    }


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (!userVisibleHint) {
            mRVListVideoKit?.stopPlay()
        }else{
            recyclerView?.postDelayed({
                mRVListVideoKit?.pendingStopPlay = false
                mRVListVideoKit?.mDy=1
                mRVListVideoKit?.initPendingPlay()
            },800)
            app_jhapp_video_imp()
        }
    }

    var hidden: Boolean = true;
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        this.hidden = hidden
        if (hidden) {
            mRVListVideoKit?.stopPlay()
        }
    }

    override fun choosed() {
        super.choosed()
        recyclerView?.postDelayed({
            mRVListVideoKit?.pendingStopPlay = false
            mRVListVideoKit?.mDy=1
            mRVListVideoKit?.initPendingPlay()
        },800)
        if(isAdded){
            app_jhapp_video_imp()
        }
    }
    override fun onDestroy() {
        adapter?.destroy()
        mRVListVideoKit?.onDestroy()
        super.onDestroy()
    }


    override fun f5() {
        if (recyclerView.childCount > 0) {
            recyclerView.scrollToPosition(0)
            refreshLayout.setEnableRefresh(true)
            refreshLayout.autoRefresh(200)
        }
    }

    override fun gun() {

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNotIntresting(event: NotIntrestEvent) {
        val list = adapter?.data
        list?.let {
            for (i in it.indices) {
                if (it[i].id == event.id) {
                    list.remove(list[i])
                    adapter?.notifyDataSetChanged()
                }
            }
        }

    }
    private var dataReady = false
    private val app_jhapp_video_impRunable :Runnable= Runnable {
        ExposurePoolService.getExecutorService().execute{
            try {
                TXReportManager.getExposureArticles(recyclerView,adapter?.data)?.forEach {obj->
                    TXReportManager.getInstance().app_jhapp_video_imp(
                        catalogItem?.name,
                        obj
                    )
                }
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }
    private fun app_jhapp_video_imp(){
        if (!dataReady)return
        recyclerView?.apply {
            removeCallbacks(app_jhapp_video_impRunable)
            postDelayed(app_jhapp_video_impRunable, TXReportManager.EXPOSURE_DELAY)
        }
    }
}